package com.zhao.dota.controller;

import cn.hutool.core.util.NumberUtil;
import com.zhao.dota.struct.Result;
import com.zhao.dota.vo.FileVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${server.tomcat.basedir}")
    private String tempPath;

    @GetMapping("/replays")
    public Result<List<FileVo>> replays() {
        File file = new File(tempPath);
        File[] files = file.listFiles((dir, fileName) -> fileName.contains(".dem"));
        if (files == null) {
            files = new File[0];
        }
        List<FileVo> fileNames = Arrays.stream(files).map(f -> {
            FileVo fileVo = new FileVo();
            fileVo.setName(f.getName());
            fileVo.setLength(f.length());
            fileVo.setLastModified(new Date(f.lastModified()));
            fileVo.setLengthFormat(NumberUtil.round(f.length() * 1.0d / 1024 / 1024, 2) + "MB");
            return fileVo;
        }).collect(Collectors.toList());
        return Result.success(fileNames);
    }


}
